<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search v-model="searchValue" placeholder="搜索服务项目" shape="round" background="#f5f5f5" @click="toSearch" />
    </div>

    <!-- 大分类导航栏 -->
    <div class="main-categories">
      <div class="main-categories-scroll">
        <div v-for="category in mainCategories" :key="category.categoryid" class="main-category-item"
          :class="{ active: activeMainCategory === category.categoryid }"
          @click="switchMainCategory(category.categoryid)">
          {{ category.categoryname }}
        </div>
        <div class="expand-btn" @click="showCategoryPopup = true">
          <van-icon name="arrow-down" />
        </div>
      </div>
    </div>

     <van-popup v-model="showCategoryPopup" position="top" :style="{ height: '40%' }">
      <div class="category-popup">
        <div class="popup-header">
          <h3>全部分类</h3>
          <van-icon name="cross" @click="showCategoryPopup = false" />
        </div>
        <div class="popup-content">
          <div v-for="category in mainCategories" :key="category.categoryid" class="popup-category-item"
            :class="{ active: activeMainCategory === category.categoryid }"
            @click="selectCategoryFromPopup(category.categoryid)">
            <van-icon :name="getCategoryIcon(category.categoryid)" />
            <span>{{ category.categoryname }}</span>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 左侧小分类（仅限前三个大分类） -->
      <div class="sub-categories" v-if="showSubCategories">
        <div v-for="subCategory in currentSubCategories" :key="subCategory.categoryid" class="sub-category-item"
          :class="{ active: activeSubCategory === subCategory.categoryid }"
          @click="switchSubCategory(subCategory.categoryid)">
          {{ subCategory.categoryname }}
        </div>
      </div>

      <!-- 服务网格 -->
      <div class="services-grid" :class="showSubCategories ? 'services-grid-three' : 'services-grid-four'
        ">
        <div class="service-item" v-for="service in currentServices" :key="service.serviceId" @click="toService(service.serviceId)">
          <div class="service-icon">
            <img :src="service.servicePicture" alt="" style="width: 46px; border-radius: 6px;"> <!-- 服务图片,从后端获取 -->
          </div>
          <div class="service-name">{{ service.serviceName }}</div>
        </div>
      </div>
    </div>

    <!-- 底部导航栏
    <div class="footer-nav">
      <van-tabbar v-model="activeNav" @change="onTabChange">
        <van-tabbar-item name="home" icon="home-o">首页</van-tabbar-item>
        <van-tabbar-item name="category" icon="apps-o" dot>分类</van-tabbar-item>
        <van-tabbar-item name="order" icon="orders-o">订单</van-tabbar-item>
        <van-tabbar-item name="mine" icon="user-o">我的</van-tabbar-item>
      </van-tabbar>
    </div> -->
  </div>
</template>

<script setup>
// 1. 导入所需 API 和组件（工程化规范：明确依赖）
import { ref, computed, onMounted, nextTick } from "vue";
import { Search, Icon, Tabbar, TabbarItem } from "vant";
import { useUserStore } from "@/stores/user";
import { findBigType, findSmallType, findService } from "@/api";
import { useRouter } from "vue-router";

// 2. 响应式数据（替代 Options API 的 data）
const searchValue = ref("");
const activeMainCategory = ref("1"); // 当前激活的大分类
const activeSubCategory = ref("1"); // 当前激活的小分类
const activeNav = ref("category"); // 底部导航激活项
const userStore = useUserStore();
const router = useRouter();

// 3. 静态数据（可抽离到单独的 data.js 文件，此处简化）
// 大分类数据
const mainCategories = ref([
]);

onMounted(() => {
  getCategory();
  getService();
  
  // 动态添加服务映射示例（可以根据实际需要添加更多）
  // addServiceMapping(3, "furnitureassembly", "家具组装");
  // addServiceMapping(4, "appliancerepair", "家电维修");
  
  console.log('服务路由映射已初始化');
  console.log('当前ID映射:', Object.keys(serviceRouteMap));
  console.log('当前名称映射:', Object.keys(serviceNameRouteMap));
})

const getCategory = async () => {
  try {
    // 1. 获取大分类数据
    let ret = await findBigType();
    const rawData = ret.data;
    
    // 2. 获取小分类数据
    ret = await findSmallType();
    subCategories.value = ret.data;
    console.log("subCategories ==>", subCategories.value);

    // 3. 处理大分类数据（添加 hasSub 标识）
    mainCategories.value = rawData.map(cat => {
      const hasSub = subCategories.value.some(sub => sub.categorytype === cat.categoryid);
      return { ...cat, hasSub };
    });
    console.log("mainCategories ==>", mainCategories.value);

    // 4. 初始化：若有大分类，默认选中第一个大分类，并自动选中其第一个小分类
    if (mainCategories.value.length > 0) {
      // 触发大分类切换（使用已定义的 switchMainCategory 方法）
      switchMainCategory(mainCategories.value[0].categoryid);
    }
  } catch (e) {
    ElMessage({
      message: e,
      type: "error"
    })
  }
}

const getService = async () => {
  try {
    let ret = await findService();
    allServices.value = ret.data;
    userStore.newType = ret
  } catch (e) {
    ElMessage({
      message: e,
      type: "error"
    })
  }
}

// 在setup函数中添加以下内容
const showCategoryPopup = ref(false);

// 从弹窗中选择分类
const selectCategoryFromPopup = (categoryId) => {
  switchMainCategory(categoryId);
  showCategoryPopup.value = false;
};

// 获取分类图标
const getCategoryIcon = (categoryId) => {
  const icons = {
    1: "home-o",
    2: "tv-o",
    3: "wrench-o",
    4: "brush-o",
    5: "cart-o",
    6: "more-o",
  };
  return icons[categoryId] || "more-o";
};

// 小分类数据
const subCategories = ref([
]);

// 所有服务数据
const allServices = ref([
]);

// 4. 计算属性（逻辑复用，响应式依赖）
// 是否显示小分类（基于当前大分类的 hasSub 属性）
const showSubCategories = computed(() => {
  const currentMainCat = mainCategories.value.find(
    (cat) => cat.categoryid === activeMainCategory.value
  );
  return currentMainCat ? currentMainCat.hasSub : false;
});

// 当前大分类下的小分类（过滤出 mainId 匹配的小分类）
const currentSubCategories = computed(() => {
  return subCategories.value.filter(
    (sub) => sub.categorytype === activeMainCategory.value
  );
});

// 当前要显示的服务（根据大/小分类过滤）
const currentServices = computed(() => {
  if (showSubCategories.value) {
    // 有小分类：同时匹配大分类 ID 和小分类 ID
    return allServices.value.filter(
      (service) =>
        service.categoryId === activeSubCategory.value
    );
  } else {
    // 无小分类：只匹配大分类 ID
    return allServices.value.filter(
      (service) => service.categoryId === activeMainCategory.value
    );
  }
});

// 服务ID与路由名称的映射关系
const serviceRouteMap = {
  // 长数字ID格式
  1980929967504252930: "cabinetrepair",        // 柜类维修
  1980930372321697794: "curtaininstallation",  // 窗帘安装
  
  // 字符串ID格式（兼容性处理）
  "1980929967504252930": "cabinetrepair",      // 柜类维修
  "1980930372321697794": "curtaininstallation", // 窗帘安装
  
  // 简单数字ID格式（向后兼容）
  1: "cabinetrepair",        // 柜类维修
  2: "curtaininstallation",  // 窗帘安装
  
  // 可以根据需要添加更多服务映射
  // 3: "furnitureassembly",    // 家具组装
  // 4: "appliancerepair",      // 家电维修
};

// 服务名称到路由的映射（备用方案）
const serviceNameRouteMap = {
  "柜类维修": "cabinetrepair",
  "窗帘安装": "curtaininstallation",
  "cabinet": "cabinetrepair",
  "curtain": "curtaininstallation"
};

// 添加新服务映射的辅助函数
const addServiceMapping = (serviceId, routeName, serviceName = '') => {
  // 添加数字和字符串形式的ID映射
  serviceRouteMap[serviceId] = routeName;
  serviceRouteMap[String(serviceId)] = routeName;
  
  // 如果提供了服务名称，也添加名称映射
  if (serviceName) {
    serviceNameRouteMap[serviceName] = routeName;
  }
  
  console.log(`已添加服务映射: ${serviceId} -> ${routeName}${serviceName ? ` (${serviceName})` : ''}`);
};

function toService(serviceId){
  console.log('点击服务，serviceId:', serviceId);
  console.log('serviceId类型:', typeof serviceId);
  
  // 查找对应的服务对象
  const service = allServices.value.find(s => s.serviceId === serviceId);
  console.log('找到的服务对象:', service);
  
  // 尝试多种方式匹配serviceId
  let routeName = serviceRouteMap[serviceId];
  
  // 如果直接匹配失败，尝试类型转换
  if (!routeName) {
    // 尝试转换为字符串
    const stringId = String(serviceId);
    routeName = serviceRouteMap[stringId];
    console.log('尝试字符串匹配:', stringId, '结果:', routeName);
  }
  
  if (!routeName) {
    // 尝试转换为数字
    const numberId = Number(serviceId);
    if (!isNaN(numberId)) {
      routeName = serviceRouteMap[numberId];
      console.log('尝试数字匹配:', numberId, '结果:', routeName);
    }
  }
  
  // 如果还是没找到，尝试通过服务名称匹配
  if (!routeName && service && service.serviceName) {
    routeName = serviceNameRouteMap[service.serviceName];
    console.log('尝试服务名称匹配:', service.serviceName, '结果:', routeName);
    
    // 如果服务名称也没匹配到，尝试模糊匹配
    if (!routeName) {
      const serviceName = service.serviceName.toLowerCase();
      if (serviceName.includes('柜') || serviceName.includes('cabinet')) {
        routeName = "cabinetrepair";
        console.log('模糊匹配到柜类维修');
      } else if (serviceName.includes('窗帘') || serviceName.includes('curtain')) {
        routeName = "curtaininstallation";
        console.log('模糊匹配到窗帘安装');
      }
    }
  }
  
  console.log('最终找到的路由名称:', routeName);
  console.log('所有可用的映射键:', Object.keys(serviceRouteMap));
  
  if (routeName) {
    console.log('跳转到路由:', routeName);
    try {
      router.push({
        name: routeName,
        query: { 
          serviceId: serviceId,
          serviceName: service ? service.serviceName : ''
        } // 将serviceId和服务名称作为查询参数传递
      });
      console.log('路由跳转成功');
    } catch (error) {
      console.error('路由跳转失败:', error);
    }
  } else {
    console.warn('未找到serviceId对应的路由:', serviceId);
    console.log('当前serviceId:', serviceId, '类型:', typeof serviceId);
    console.log('服务名称:', service ? service.serviceName : '未知');
    // 默认跳转到柜类维修页面
    try {
      router.push({
        name: "cabinetrepair",
        query: { 
          serviceId: serviceId,
          serviceName: service ? service.serviceName : '',
          fallback: true
        }
      });
      console.log('默认路由跳转成功');
    } catch (error) {
      console.error('默认路由跳转失败:', error);
    }
  }
}

// 5. 事件处理函数
// 切换大分类（重置小分类为第一个）
const switchMainCategory = (categoryId) => {
  activeMainCategory.value = categoryId;
  // 等待计算属性更新（使用 nextTick 确保 currentSubCategories 已刷新）
  nextTick(() => {
    // 若当前大分类有小分类，且小分类列表不为空，自动激活第一个
    if (showSubCategories.value && currentSubCategories.value.length > 0) {
      activeSubCategory.value = currentSubCategories.value[0].categoryid; // 注意：确保小分类的 ID 字段是 id
    } else {
      // 若没有小分类，重置小分类（可选）
      activeSubCategory.value = "";
    }
  });
};

// 切换小分类
const switchSubCategory = (subCategoryId) => {
  activeSubCategory.value = subCategoryId;
};

// 搜索事件
const toSearch = (value) => {
  console.log("前往搜索页面");
  router.push("search")
  // 实际项目可添加：过滤 allServices 实现搜索功能
  // 示例：currentServices.value = allServices.value.filter(service => service.name.includes(value))
  // router.push({name:"search"}) 
};

// 底部导航切换事件
// const onTabChange = (name) => {
//   console.log("切换到底部导航:", name);
//   // 实际项目可添加：路由跳转逻辑（如使用 vue-router）
//   // 示例：useRouter().push(`/${name}`)
//   router.push({name:`${name}`})
// };

// 6. 注册 Vant 组件（局部注册，减少全局污染）
const VantComponents = {
  VanSearch: Search,
  VanIcon: Icon,
  VanTabbar: Tabbar,
  VanTabbarItem: TabbarItem,
};
</script>

<style scoped>
/* 基础样式：scoped 确保样式仅作用于当前组件 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica,
    sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

.page-container {
  max-width: 750px;
  margin: 0 auto;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 50px;
  /* 给底部导航留空间 */
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #ff6b35, #ff8e53);
  color: white;
  padding: 15px;
  text-align: center;
}

.header h1 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}

.header p {
  font-size: 14px;
  opacity: 0.9;
}

/* 搜索栏样式 */
.search-bar {
  padding: 10px 15px;
  background-color: #fff;
}

/* 大分类导航样式 */
.main-categories {
  background-color: #fff;
  padding: 10px 0;
}

.main-categories-scroll {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0 15px;
  scrollbar-width: none;
  /* 隐藏 Firefox 滚动条 */
}

.main-categories-scroll::-webkit-scrollbar {
  display: none;
  /* 隐藏 Chrome 滚动条 */
}

.main-category-item {
  display: inline-block;
  padding: 8px 16px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 14px;
  background-color: #f5f5f5;
  color: #666;
  cursor: pointer;
  transition: all 0.2s ease;
  /* 平滑过渡 */
}

.main-category-item.active {
  background-color: #ff6b35;
  color: white;
}

.expand-btn {
  width: 40px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 15px;
  margin-right: 10px;
  flex-shrink: 0;
}

.category-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
}

.popup-content {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  padding: 15px;
  overflow-y: auto;
}

.popup-category-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background-color: #f8f8f8;
  border-radius: 8px;
  font-size: 14px;
}

.popup-category-item.active {
  background-color: #fff2e8;
  color: #ff6b35;
}

.popup-category-item .van-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 内容区域样式 */
.content-area {
  display: flex;
  margin-top: 10px;
  height: calc(100vh - 200px);
  /*固定高度，实现滚动*/
}

/* 左侧小分类样式 */
.sub-categories {
  width: 100px;
  height: 100%;
  background-color: #f9f9f9;
  overflow-y: auto;
  border: 1px solid black;
  scrollbar-width: none;
  /* 细滚动条 */
}

.sub-category-item {
  padding: 15px 10px;
  font-size: 14px;
  text-align: center;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sub-category-item.active {
  background-color: #fff;
  color: #ff6b35;
  font-weight: bold;
  border-left: 3px solid #ff6b35;
}

/* 服务网格样式 */
.services-grid {
  flex: 1;
  padding: 10px 15px;
  overflow-y: auto;
  scrollbar-width: thin;
}

.services-grid-three {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.services-grid-four {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
}

.service-icon {
  width: 50px;
  height: 50px;
  background-color: #f8f8f8;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.service-name {
  font-size: 12px;
  color: #333;
  line-height: 1.4;
}

/* 底部导航样式 */
.footer-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 750px;
  margin: 0 auto;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 999;
  /* 确保在最上层 */
}
</style>
